package com.zf.yichat.api.controller.user;

import com.alibaba.fastjson.JSON;
import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.api.dto.request.RegisterRequest;
import com.zf.yichat.api.dto.resp.RegisterDto;
import com.zf.yichat.mapper.UserIntegralDetailMapper;
import com.zf.yichat.mapper.UserIpMapper;
import com.zf.yichat.mapper.UserMapper;
import com.zf.yichat.model.*;
import com.zf.yichat.service.*;
import com.zf.yichat.service.config.ConfigSet;
import com.zf.yichat.service.config.RedisService;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.N3d;
import com.zf.yichat.utils.common.Sign;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.DictKey;
import com.zf.yichat.vo.IntegralType;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 用户注册
 *
 * @author fengsong
 * @date create in 15:10 2019/5/28 2019
 */
@Controller
public class RegisterController extends BaseController {

    @Autowired
    private FriendService friendService;
    @Autowired
    private UserInviteService userInviteService;
    @Autowired
    private PacketService packetService;

    @Autowired
    private UserService userService;
    @Autowired
    private TicketsService ticketsService;
    @Autowired
    private UserIntegralService userIntegralService;
    @Autowired
    private AppConfigService appConfigService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private SysDictService sysDictService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserIntegralDetailMapper userIntegralDetailMapper;
    @Autowired
    private PlantTreeService plantTreeService;

    @Autowired
    private UserIpMapper userIpMapper;
    private static final Logger logger = LoggerFactory.getLogger(Sign.class);

    @RequestMapping("user/register_for_rc")
    @ResponseBody
    public FsResponse register(@RequestBody RegisterRequest request) throws Exception {
        request.valid();


//        String ip = GeneralUtils.getIpAddress(re);
        String clientIp = request.getClientIp();
        if (StringUtils.isNotBlank(clientIp) && appConfigService.isFreezeIp(clientIp)) {
            return FsResponseGen.fail(YiChatMsgCode.LOGIN_IP_FREEZE);
        }

//        if (userService.selectByMobile(request.getMobile()) != null) {
//            return FsResponseGen.fail(configSet.isMobileAppIdStatus() ? YiChatMsgCode.REGISTER_MOBILE_APPID_EXIST : YiChatMsgCode.REGISTER_MOBILE_EXIST);
//        }
        User user = userService.selectByMobile(request.getMobile());
        if (Objects.isNull(user)) {

            String deviceId = request.getDeviceId();
            //用新生用户id来做设备id的标识字段
            Example exampleCheckDevice = new Example(User.class);
            exampleCheckDevice.createCriteria().andEqualTo("xspayuserid", deviceId);

            exampleCheckDevice.setOrderByClause(" id desc limit 1");
            User userCheckDevice = userMapper.selectOneByExample(exampleCheckDevice);
            if (!Objects.isNull(userCheckDevice)) {
                //已经有用户用这个设备注册了。不可以再注册
                return FsResponseGen.failMsg("单设备只能注册一个账号");
            }


            user = request.generateUser();
            user.setXspayuserid(deviceId);

            String checkRecommendCode = request.getRecommendCode();
            if (!"235b2g4824dxs".equals(checkRecommendCode)) {
                //非内部渠道注册用户
                //查询推荐码是否存在
                if (StringUtils.isNotBlank(checkRecommendCode)) {
                    try {
                        // 不是后台批量注册需要校验上级邀请码是否存在
                        if (!checkRecommendCode.contains("a1d2m3i4n5|")) {
                            User userCheckHasRec=userService.selectByCode(request.getRecommendCode());
                            if(userCheckHasRec==null){
                                return FsResponseGen.fail(YiChatMsgCode.USER_INFO_INVITE_CODE_NONE);

                            }
                        }
                    }catch (Exception e){
                        return FsResponseGen.fail(YiChatMsgCode.USER_INFO_INVITE_CODE_MULTI);

                    }

//                        if (codeList != null && Arrays.asList(codeList).contains(request.getRecommendCode())) {
//                            user.setRecommendCode(request.getRecommendCode());
//                        } else {
//                            return FsResponseGen.fail(YiChatMsgCode.USER_INFO_INVITE_CODE_NONE);
//                        }
                } else {
                    return FsResponseGen.failMsg("必须填写邀请码");
                }
            }

            String recommendCode = request.getRecommendCode();
            if (!checkRecommendCode.contains("a1d2m3i4n5|")) {
                user.setRecommendCode(recommendCode);
            }
            else {
                String[] splitCode = recommendCode.split("\\|");
                user.setRecommendCode(splitCode[1]);
            }

//            if(!TextUtils.isEmpty(request.getRecommendCode())){
//                Example example=new Example(User.class);
//                example.createCriteria().andEqualTo("ucode",request.getRecommendCode());
//                List<User> userCheck=userMapper.selectByExample(example);
//                if(userCheck==null||userCheck.size()==0){
//                    return FsResponseGen.fail(YiChatMsgCode.USER_INFO_INVITE_CODE_NONE);
//
//                }
//            }else {
//                user.setRecommendCode(request.getRecommendCode());
//            }

            UserIm im = userService.add(user);

            String appId = getNumber(8);


            while (!Objects.isNull(userService.selectByAppId(appId))) {
                appId = getNumber(8);
            }
            user.setAppid("A" + appId);

            userService.update(user);


//                        String hasUsedInviteCode= redisService.getVal("invite_code_list");
//                        if(hasUsedInviteCode==null){
//                            redisService.setVal("invite_code_list",inviteCode);
//                        } else {
//                            if(hasUsedInviteCode.contains(inviteCode)){
//                                return FsResponseGen.fail(YiChatMsgCode.USER_INFO_INVITE_CODE_NONE);
//                            }else {
//                                redisService.setVal("invite_code_list",hasUsedInviteCode+"#"+inviteCode);
//                            }
//                        }
        }


        RegisterDto data = new RegisterDto();
//        data.setImPassword(im.getImPassword());
        data.setToken(user.getToken());
        data.setUserId(N3d.encode(user.getId()));
        data.setAppId(user.getAppid());
        data.setMobile(user.getMobile());
        UserIp userIp = new UserIp();
        userIp.setIp(clientIp);
        userIp.setUserId(user.getId());
        userIp.setType("0");
        userIp.setCtime(new Date());
        userIpMapper.insertUseGeneratedKeys(userIp);

        // 如果有上级邀请码，赠送5次浇水次数，每日奖励10人次，也就是每日邀请超过10人，不再奖励次数
   //     String recommendCode = request.getRecommendCode();
//        User recommendUser = userService.selectByCode(recommendCode);
//        if (StringUtils.isNotBlank(recommendCode) && !recommendCode.contains("a1d2m3i4n5|")) {
//            // 查询当日邀请人数
//            int count = userService.queryInvitationsNumToday(recommendCode);
//            if (null != recommendUser && count < 10) {
//                // 当天赠送任务次数
//                Integer inviteNum = plantTreeService.queryGiveNumbersByType(recommendUser.getId(), UserPrintTreeTask.INVITE_TASK);
//                if (inviteNum < 10) {
//                    plantTreeService.addTask(recommendUser.getId(), "填写邀请码", UserPrintTreeTask.INVITE_TASK, 5);
//                }
//            }
//        }
//
//        // 赠送推荐人能量
//        if (StringUtils.isNotBlank(recommendCode) && !recommendCode.contains("a1d2m3i4n5|")) {
//            if (null != recommendUser) {
//                authenticationGiveIntegral(recommendUser.getId());
//            }
//        }

        // 赠送注册用户积分
        authenticationGiveIntegral(user.getId());
        // 用户注册赠送用户门票
        ticketsService.giveUserTickets(user.getId());
//        friendService.apply(user.getId(), 15001577l, "系统客服");

        return FsResponseGen.successData(data);
    }


    /**
     *  注册赠送积分
     * @return
     * @throws Exception
     */
    @RequestMapping("user/register_for_int")
    @ResponseBody
    public FsResponse registerForInt(@RequestBody RegisterRequest request) throws Exception {
        request.valid();

        String clientIp = request.getClientIp();
        if (StringUtils.isNotBlank(clientIp) && appConfigService.isFreezeIp(clientIp)) {
            return FsResponseGen.fail(YiChatMsgCode.LOGIN_IP_FREEZE);
        }

        User user = userService.selectByMobile(request.getMobile());
        if (Objects.isNull(user)) {

            String deviceId = request.getDeviceId();
            //用新生用户id来做设备id的标识字段
            Example exampleCheckDevice = new Example(User.class);
            exampleCheckDevice.createCriteria().andEqualTo("xspayuserid", deviceId);

            exampleCheckDevice.setOrderByClause(" id desc limit 1");
            User userCheckDevice = userMapper.selectOneByExample(exampleCheckDevice);
            if (!Objects.isNull(userCheckDevice)) {
                //已经有用户用这个设备注册了。不可以再注册
                return FsResponseGen.failMsg("单设备只能注册一个账号");
            }
            user = request.generateUser();
            user.setXspayuserid(deviceId);
            String checkRecommendCode = request.getRecommendCode();
            if (!"235b2g4824dxs".equals(checkRecommendCode)) {
                //非内部渠道注册用户
                //查询推荐码是否存在
                if (StringUtils.isNotBlank(checkRecommendCode)) {
                    try {
                        // 不是后台批量注册需要校验上级邀请码是否存在
                        if (!checkRecommendCode.contains("a1d2m3i4n5|")) {
                            User userCheckHasRec=userService.selectByCode(request.getRecommendCode());
                            if(userCheckHasRec==null){
                                return FsResponseGen.fail(YiChatMsgCode.USER_INFO_INVITE_CODE_NONE);

                            }
                        }
                    }catch (Exception e){
                        return FsResponseGen.fail(YiChatMsgCode.USER_INFO_INVITE_CODE_MULTI);

                    }
                } else {
                    return FsResponseGen.failMsg("必须填写邀请码");
                }
            }

            String recommendCode = request.getRecommendCode();
            if (!checkRecommendCode.contains("a1d2m3i4n5|")) {
                user.setRecommendCode(recommendCode);
            }
            else {
                String[] splitCode = recommendCode.split("\\|");
                user.setRecommendCode(splitCode[1]);
            }

            UserIm im = userService.add(user);
            String appId = getNumber(8);
            while (!Objects.isNull(userService.selectByAppId(appId))) {
                appId = getNumber(8);
            }
            user.setAppid("A" + appId);

            userService.update(user);
        }

        RegisterDto data = new RegisterDto();
        data.setToken(user.getToken());
        data.setUserId(N3d.encode(user.getId()));
        data.setAppId(user.getAppid());
        data.setMobile(user.getMobile());
        UserIp userIp = new UserIp();
        userIp.setIp(clientIp);
        userIp.setUserId(user.getId());
        userIp.setType("0");
        userIp.setCtime(new Date());
        userIpMapper.insertUseGeneratedKeys(userIp);

        // 赠送注册用户积分
        authenticationGiveIntegral(user.getId());

        // 用户注册赠送用户门票
        ticketsService.giveUserTickets(user.getId());
        return FsResponseGen.successData(data);
    }

    // 赠送能量
    private void authenticationGiveIntegral(Long userId){
        SysDict sysDict = sysDictService.selectOne(DictKey.user_register_give_integral);
        Integer integral = 0;
        if (null == sysDict) {
            integral = 1;
        }else {
            integral = Integer.valueOf(sysDict.getValue());
        }

        updateIntegralDetail(IntegralType.REGISTER_CONSUME, userId + ":" + User.REGISTER_TYPE, integral, userId);
    }

    /**
     * 更新用户积分
     * @param type
     * @param referId
     * @param score
     * @param userId
     */
    private void updateIntegralDetail(IntegralType type, String referId, Integer score, Long userId) {

        //增加用户积分记录
        UserIntegralDetail detail = new UserIntegralDetail();
        detail.setIntegral(score);
        detail.setReferType(type.getVal());
        detail.setMemo(type.getDesc());
        detail.setUserId(userId);
        detail.setReferId(referId);
        userIntegralDetailMapper.insertSelective(detail);

        //更新user表的积分值
        userMapper.addIntegral(score, userId);

    }

    /**
     * 随机生成字符，只有数字
     *
     * @param length id长度
     */
    public static String getNumber(Integer length) {
        String uid = "";
        for (Integer i = 0; i < length; i++) {
            String randChar = String.valueOf(Math.round(Math.random() * 9));
            uid = uid.concat(randChar);
        }
        return uid;
    }


//    @RequestMapping("user/register2")
//    @ResponseBody
//    public void register() {
//        for (int i = 0; i < 20; i++) {
//            String str = String.format("%03d", i + 1);
//            RegisterRequest request = new RegisterRequest();
//            request.setMobile("19822011" + str);
//            request.setNick("zfxm" + str);
//            request.setPlatform("android");
////            request.setPassword(GeneralUtils.randomNum(6));
//            request.setPassword("zfxm_7788");
//
//
////            whrite2txt(request.getNick() + "     " + request.getPassword());
//
//
////            request.valid();
//            if (userService.selectByMobile(request.getMobile()) != null) {
////                whrite2txt(request.getNick() + "     " + request.getPassword()+"   exist");
////                return FsResponseGen.fail(configSet.isMobileAppIdStatus() ? YiChatMsgCode.REGISTER_MOBILE_APPID_EXIST : YiChatMsgCode.REGISTER_MOBILE_EXIST);
//            }
//            User user = request.generateUser();
//            UserIm im = userService.add(user);
//        }
//
//    }
//
//    @RequestMapping("user/register3")
//    @ResponseBody
//    public void register3() {
//        packetService.packetSaleInitForSystem();
//
//    }
//
//    private void whrite2txt(String content){
//        try{
//
//            File file =new File("user.txt");
//
//            //if file doesnt exists, then create it
//            if(!file.exists()){
//                file.createNewFile();
//            }
//
//            //true = append file
//            FileWriter fileWritter = new FileWriter(file.getName(),true);
//            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
//            bufferWritter.write(content);
//            bufferWritter.newLine();
//            bufferWritter.close();
//
//            System.out.println(content);
//
//        }catch(IOException e){
//            e.printStackTrace();
//        }
//    }
}
